package handler

import (
	ds "gitee.com/shipnet/flogo_edge_channel_data_store"
	"github.com/project-flogo/core/support/log"
)

func (a *Activity) createEdgeChannel(params EdgeChannelParams, logger log.Logger) error {
	if ch, ok := a.edgeChannels[params.EdgeChannelID]; ok {
		return ch.UpdateParams(params)
	} else {
		publish := func(msg ds.EdgeChannelData) error {
			// a.outputChannel.Publish(msg)
			return a.edgeChannelDataStore.Set(msg)
		}
		ctx := Context{
			logger:      log.ChildLogger(logger, params.EdgeChannelID),
			publish:     publish,
			metricStore: a.metricDataStore,
		}
		ch, err := NewEdgeChannel(ctx, params)
		if err != nil {
			return err
		}

		a.edgeChannels[params.EdgeChannelID] = *ch

		go ch.Run()
		return nil
	}
}

func (a *Activity) deleteEdgeChannel(params edgeChannelDeleteParams) error {
	if ch, ok := a.edgeChannels[params.EdgeChannelID]; ok {
		err := ch.Stop()
		delete(a.edgeChannels, params.EdgeChannelID)
		return err
	} else {
		return nil
	}
}
